<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/3/18
 * Time: 16:53
 */
namespace common\logics\taskcommod;

use Yii;
use common\widgets\Tool;
use yii\base\BaseObject;

class TaskCommodLogic extends BaseObject implements ITaskCommod
{
    /** @var \common\sources\read\taskcommod\TaskCommodAccess $RTaskCommodAccess ****/
    private $RTaskCommodAccess;
    /** @var \common\sources\write\taskcommod\TaskCommodAccess  $WTaskCommodAccess **/
    private $WTaskCommodAccess;
    /** @var \common\sources\read\taobao\TaoBaoAccess $RTaoBaoAccess **/
    private $RTaoBaoAccess;
    /** @var \common\sources\write\taobao\TaoBaoAccess  $WTaoBaoAccess**/
    private $WTaoBaoAccess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess $RTaskOrderAccess ***/
    private $RTaskOrderAccess;
    /** @var \common\sources\write\taskorder\TaskOrderAccess $WTaskOrderAccess **/
    private $WTaskOrderAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess  $RBuyUserAccess***/
    private $RBuyUserAccess;
    /** @var \common\sources\write\buyuser\BuyUserAccess $WBuyUserAccess **/
    private $WBuyUserAccess;
    /** @var \common\sources\read\valueservice\ValueServiceAccess $RValueServiceAccess ***/
    private $RValueServiceAccess;
    /** @var \common\sources\read\shop\ShopAccess $RShopAccess **/
    private $RShopAccess;
    /** @var \common\sources\read\taskcommodkeywords\TaskCommodKeywordAccess $RTaskCommodKeywordAccess ***/
    private $RTaskCommodKeywordAccess;
    /** @var \common\sources\write\taskcommodkeywords\TaskCommodKeywordAccess $WTaskCommodKeywordAccess ***/
    private $WTaskCommodKeywordAccess;
    /**@var \common\sources\read\valueserviceprohibit\ValueServiceProhibitAccess $RValueServiceProhibitAccess **/
    private $RValueServiceProhibitAccess;
    /** @var \common\sources\read\taskshopimage\TaskShopImageAccess $RTaskShopImageAccess ***/
    private $RTaskShopImageAccess;
    /** @var \common\sources\write\taskshopimage\TaskShopImageAccess $WTaskShopImageAccess ***/
    private $WTaskShopImageAccess;
    /** @var \common\sources\read\praisekeywords\PraiseKeywordsAccess  $RPraiseKeywordsAccess **/
    private $RPraiseKeywordsAccess;
    /** @var \common\sources\write\praisekeywords\PraiseKeywordsAccess  $WPraiseKeywordsAccess **/
    private $WPraiseKeywordsAccess;
    /** @var \common\sources\read\bank\BankAccess  $RBankAccess ****/
    private $RBankAccess;
    /** @var \common\sources\write\taskorderlog\BuyTaskOrderLogAccess  $WBuyTaskOrderLogAccess  ***/
    private $WBuyTaskOrderLogAccess;

    public function init()
    {
        $this->RTaskCommodAccess = Yii::$container->get("RTaskCommodAccess");
        $this->WTaskCommodAccess = Yii::$container->get("WTaskCommodAccess");
        $this->RTaoBaoAccess = Yii::$container->get("RTaoBaoAccess");
        $this->WTaoBaoAccess = Yii::$container->get("WTaoBaoAccess");
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->WTaskOrderAccess = Yii::$container->get("WTaskOrderAccess");
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->WBuyUserAccess = Yii::$container->get("WBuyUserAccess");
        $this->RValueServiceAccess = Yii::$container->get("RValueServiceAccess");
        $this->RShopAccess = Yii::$container->get("RShopAccess");
        $this->RTaskCommodKeywordAccess = Yii::$container->get("RTaskCommodKeywordAccess");
        $this->WTaskCommodKeywordAccess = Yii::$container->get("WTaskCommodKeywordAccess");
        $this->RValueServiceProhibitAccess = Yii::$container->get("RValueServiceProhibitAccess");
        $this->RTaskShopImageAccess = Yii::$container->get("RTaskShopImageAccess");
        $this->WTaskShopImageAccess = Yii::$container->get("WTaskShopImageAccess");
        $this->RBankAccess = Yii::$container->get("RBankAccess");
        $this->RPraiseKeywordsAccess = Yii::$container->get("RPraiseKeywordsAccess");
        $this->WPraiseKeywordsAccess = Yii::$container->get("WPraiseKeywordsAccess");
        $this->WBuyTaskOrderLogAccess = Yii::$container->get("WBuyTaskOrderLogAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function getTaskList($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }
        if(empty($data['plat_type']))
        {
            return Tool::returnJson([],402,"平台不能为空");
        }
        if(empty($data['tb_id']))
        {
            return Tool::returnJson([],407,"您未绑定买号，请前去绑定买号");
        }
        $page_num = $data['page_num'];
        $limit = $data['limit'];
        //获取买号用户信息
        $taobao = $this->RTaoBaoAccess->getTaoBaoDetail($data['tb_id']);
        if(empty($taobao))
        {
            return Tool::returnJson([],408,"买号不存在,请重新选择");
        }
        //查询一个月内接过任务的店铺id
        $task_order_shop_arr = $this->RTaskOrderAccess->getTaskOrderByShopId($data['tb_id'],strtotime(date('Y-m-d', strtotime("-30 day"))),strtotime(date('Y-m-d',time())." 23:59:59"),"1,2,3,4,5,6,7,8,9,12,13");
        $shop_ids  = '';
        if(count($task_order_shop_arr) >0)
        {
            $shop_id_arr = array_column($task_order_shop_arr,"shop_id");
            $shop_ids = implode(',',$shop_id_arr);
        }
        $data['shop_ids'] = $shop_ids;

        //任务类型
        $task_types = Yii::$app->params['plat_task_type'][$data['plat_type']];
        foreach ($task_types as &$task_type)
        {
            $task_type['price'] = number_format($task_type['price'],2,".","");
        }

        $count = $this->RTaskCommodAccess->getTaskCommodCount($data);
        $list = [];
        if($count >0)
        {
            $list = $this->RTaskCommodAccess->getList($data);
            $value_services = [];
            if($data['task_class'] == 3)
            {
                $task_commodArr = array_column($list,"id");
                $task_commod_ids = implode(",",$task_commodArr);
                $value_services = $this->RValueServiceAccess->getValueServiceReturnType($task_commod_ids);
            }
            foreach ($list as &$item)
            {
                if($data['task_class'] == 3)
                {
                    foreach ($value_services as $values)
                    {
                        if($item['id'] == $values['task_commod_id'])
                        {
                            $item['reword_commise'] = number_format($values['reword_commise'],2,".","");
                        }
                    }
                }


                $item['task_status'] = isset($item['task_status']) ? Yii::$app->params['task_status'][$item['task_status']]: "未知状态";
                $item['return_type_name'] = $item['return_type'] == '1' ? "平台返款": ($item['return_type'] == '2'? "商家返款": "未返款方式");
            }
        }
        //各种任务类型统计
        $pc_count = $this->RTaskCommodAccess->getTaskCommodCount(['plat_type' =>$data['plat_type'],"port_type" =>1,"shop_ids"=>$shop_ids ]);
        $phone_count = $this->RTaskCommodAccess->getTaskCommodCount(['plat_type' =>$data['plat_type'],'port_type' =>2,"shop_ids"=>$shop_ids]);
        $words_count = $this->RTaskCommodAccess->getTaskCommodCount(['plat_type' =>$data['plat_type'],'port_type' =>$data['port_type'],"task_type" =>1,"shop_ids"=>$shop_ids]);
        $image_count = $this->RTaskCommodAccess->getTaskCommodCount(['plat_type' =>$data['plat_type'],'port_type' =>$data['port_type'],"task_type" =>2,"shop_ids"=>$shop_ids]);
        $gr_code_count = $this->RTaskCommodAccess->getTaskCommodCount(['plat_type' =>$data['plat_type'],'port_type' =>$data['port_type'],"task_type" =>4,"shop_ids"=>$shop_ids]);

        $count_object = [
            "pc_count" => $pc_count,
            "phone" => $phone_count,
            "word_count" => $words_count,
            "image_count" => $image_count,
            "gr_code_count" => $gr_code_count,
        ];

        return Tool::returnJson([
            "list" => $list,
            "limit" => $limit,
            "count" => $count,
            "task_type" => $task_types,
            "page_num" => $page_num,
            "count_object" => $count_object,
        ],200,"成功");
    }
    //买手接任务
    public function receiveTasks($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }

        if(empty($data['task_commod_id']))
        {
            return Tool::returnJson([],402,"主任务id不能为空");
        }
        if(empty($data['tb_id']))
        {
            return Tool::returnJson([],403,"绑定买号id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],405,"安全码不能为空");
        }
        if(md5($data['buy_id'].$data['task_commod_id'].$data['tb_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],406,"安全码不正确");
        }
        //判断买手用户是否存在
        $buy = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buy))
        {
            return Tool::returnJson([],407,"买手不存在");
        }
        if($buy['role'] !=1)
        {
            return Tool::returnJson([],408,"商家账号不能接单");
        }

        //买手地址
        $band = $this->RTaoBaoAccess->getTaoBaoDetail($data['tb_id']);
        if(empty($band))
        {
            return Tool::returnJson([],409,"买号id不存在");
        }
        //查看绑定银行卡信息
//        $band_bank = $this->RBankAccess->getBuyUserBankStatusAccount($data['buy_id']);
//        if(empty($band_bank))
//        {
//            return Tool::returnJson([],6000,"买号没有可提现的银行账号");
//        }
        //判断该任务订单已经做完
        $task_commod = $this->RTaskCommodAccess->getTaskDetail($data['task_commod_id']);
        if(empty($task_commod))
        {
            return Tool::returnJson([],410,"任务不存在");
        }
        if($task_commod['task_status'] != 4)
        {
            return Tool::returnJson([],411,"非进行中任务不可接");
        }
        if($task_commod['surplus_task_num'] == 0)
        {
            return Tool::returnJson([],412,"任务已经接完");
        }
        //判断是否有未完成的任务
        $no_submit_count = $this->RTaskOrderAccess->getBuyTaskOrderCount($data['buy_id'],1);
        if($no_submit_count>0)
        {
            return Tool::returnJson([],426,"买手必须完成已经接手任务，才能接下一个任务");
        }
        //判断买手的任务是否已经接过该任务
        $task_order_count = $this->RTaskOrderAccess->getTaskOrderByTaskCommodId($data['buy_id'],$data['task_commod_id']);
        if($task_order_count >0)
        {
            return Tool::returnJson([],428,"你已经接过次任务不能重置接");
        }
        //一个买号在一个月内是否接过同样的店铺商品
        $shopId_arr = $this->RTaskOrderAccess->getTaskOrderByShopId($data['tb_id'],strtotime(date('Y-m-d', strtotime("-30 day"))),strtotime(date('Y-m-d',time())." 23:59:59"),"1,2,3,4,5,6,7,8,9,12,13");
        if(!empty($shopId_arr))
        {
            $shop_id_arr = array_column($shopId_arr,"shop_id");
            if(in_array($task_commod['shop_id'],$shop_id_arr))
            {
                return Tool::returnJson([],458,"该店铺任务已经接完");
            }
        }

        //每天只能接3单
        $recieve_order_count = $this->RTaskOrderAccess->getTaskTidCount($data['tb_id'],"1,2,3,4,5,6,7,8,9,12,13",strtotime(date('Y-m-d',time())),strtotime(date('Y-m-d',time())." 23:59:59"));
        if($recieve_order_count >=3)
        {
            return Tool::returnJson([],430,"每个买号每天接任务次数不能超过3单");
        }
        //最近7天限制
        $week_count = $this->RTaskOrderAccess->getTaskTidCount($data['tb_id'],"1,2,3,4,5,6,7,8,9,12,13",strtotime(date('Y-m-d', strtotime("-7 day"))),strtotime(date('Y-m-d',time())." 23:59:59"));
        if($week_count >=15)
        {
            return Tool::returnJson([],435,"每个买号每周接任务次数不能超过15单");
        }
        //30 天内最多50 单
        $month_count = $this->RTaskOrderAccess->getTaskTidCount($data['tb_id'],"1,2,3,4,5,6,7,8,9,12,13",strtotime(date('Y-m-d', strtotime("-30 day"))),strtotime(date('Y-m-d',time())." 23:59:59"));
        if($month_count >=50)
        {
            return Tool::returnJson([],439,"每个买号每周接任务次数不能超过50单");
        }
        //查询店铺信息
        $shop = $this->RShopAccess->getBusShopDetial(["id" => $task_commod['shop_id']]);
        if(empty($shop))
        {
            return Tool::returnJson([],6000,"商家店铺信息异常");
        }
        $keywords = '';
        $task_commod_keywords_id = 0;
        $use_num = 0;
        if(($task_commod['plat_type'] == 1 || $task_commod['plat_type'] == 2) && $task_commod['task_type'] != 4)
        {
            //获取主任务对应的关键字
            $task_commod_keywords = $this->RTaskCommodKeywordAccess->getTaskCommodKeyword($data['task_commod_id']);
            if(count($task_commod_keywords) >0)
            {
                $task_commod_round = $task_commod_keywords[rand(0,count($task_commod_keywords)-1)];
                $keywords = $task_commod_round['word'];
                $task_commod_keywords_id = $task_commod_round['id'];
                $use_num = $task_commod_round['use_num'];
            }else
            {
                return Tool::returnJson([],3000,"任务已经接完");
            }
        }

        $value_service = $this->RValueServiceAccess->getValueServiceByCommodId($data['task_commod_id']);
        if(empty($value_service))
        {
            return Tool::returnJson([],413,"任务编号异常");
        }
        //判断买号年龄和性别是否接次任务
        if($value_service['buy_sex']>1)
        {
            $sex_num = $band['sex']== '男'? 2:($band['sex']== '女'? 3:1);
            if($value_service['buy_sex'] != $sex_num)
            {
                return Tool::returnJson([],2500,"买号跟服务类型不匹配");
            }
        }
        //增值服务年龄区间
        if(!empty($value_service['buy_age']))
        {
            $age_arr = explode("-",$value_service['buy_age']);
            if($band['zfbage']<$age_arr[0] || $band['zfbage']>$age_arr[1])
            {
                return Tool::returnJson([],2580,"买号年龄不匹配");
            }
        }
        $data['express_type'] = $value_service['expre_service'];

        //判断 是否有禁止地址
        $value_serviceprohibit = $this->RValueServiceProhibitAccess->getValueServiceProhibit($value_service['id']);
        if(count($value_serviceprohibit) >0)
        {
            $area_prohibit_arr = array_column($value_serviceprohibit,"city_code");
            if(in_array($band['city_code'],$area_prohibit_arr))
            {
                return Tool::returnJson([],415,"该地区买号不能接此任务");
            }
            $pro_prohibit_arr = array_column($value_serviceprohibit,"pro_code");
            if(in_array($band['pro_code'],$pro_prohibit_arr))
            {
                return Tool::returnJson([],416,"该地区买号不能接此任务");
            }
        }
        //判断任务是否是非图文任务
        $praise_keywords = '';
        $praise_keywords_id = 0;
        if(!(($task_commod['plat_type'] == 1 || $task_commod['plat_type'] == 2) && $task_commod['task_type'] == 2))
        {
            if($value_service['praise'] == 3)
            {
                //如果是自定义好评关键字
                $praise_arr = $this->RPraiseKeywordsAccess->getPraiseKeywords($value_service['id']);
                if(count($praise_arr)>0)
                {
                    $praise = $praise_arr[rand(0,count($praise_arr)-1)];
                    $praise_keywords = $praise['word'];
                    $praise_keywords_id = $praise['id'];
                }
            }
        }

        $data['bus_id'] = $task_commod['bus_id'];
        $data['port_type'] = $task_commod['port_type'];
        $data['tbname'] = $band['tbname'];
        $data['main_url1'] = $task_commod['main_url1'];
        $data['main_url2'] = $task_commod['main_url2'];
        $data['title'] = $task_commod['title'];
        $data['plat_type'] = $task_commod['plat_type'];
        $data['task_type'] = $task_commod['task_type'];
        $data['price'] = $task_commod['price'];
        $data['num'] = $task_commod['num'];
        $data['size'] = $task_commod['size'];
        $data['colour'] = $task_commod['colour'];
        $data['range_price'] = $task_commod['range_price'];
        $data['ww_name'] = $shop['ww_name'];
        $data['qr_code_url'] = $task_commod['qr_code_url'];
        $data['keywords'] = $keywords;

        $data['actual_price'] = $task_commod['price'] * $task_commod['num'];
        $data['ship_addr'] = $task_commod['ship_addr'];
        $data['shop_name'] = $task_commod['shop_name'];
        $data['task_id'] = $task_commod['task_id'];
        $data['advance_amount'] = 0;
        $data['commission'] = number_format($task_commod['buy_get_commisse'] + $value_service['reword_commise'],2,".","");
        $data['receive_name'] = $band['takename'];
        $data['receive_phone'] = $band['takephone'];
        $data['pro_name'] = $band['pro_name'];
        $data['pro_code'] = $band['pro_code'];
        $data['city_name'] = $band['city_name'];
        $data['city_code'] = $band['city_code'];
        $data['area_name'] = $band['area_name'];
        $data['area_code'] = $band['area_code'];
        $data['addr'] = $band['addr'];
        $data['shop_id'] = $task_commod['shop_id'];
        $data['task_commod_keyword_id'] = $task_commod_keywords_id;

        $data['praise_keywords'] = $praise_keywords;
        $data['return_type'] = $task_commod['return_type'];
        //判断该用户是否已经接过该任务
        $task_order = $this->RTaskOrderAccess->getTaskOrderLists($data['task_commod_id']);
        if($task_commod['task_num'] <= count($task_order))
        {
            return Tool::returnJson([],417,"任务已经接完");
        }
        $buy_arr = array_column($task_order,"buy_id");
        if(in_array($data['buy_id'],$buy_arr))
        {
            return Tool::returnJson([],418,"已接过的任务不能再接");
        }
        //判断是否是图文任务
        if(($task_commod['plat_type'] == 1 || $task_commod['plat_type'] == 2) && $task_commod['task_type'] == 2)
        {
            //是图文任务
            //获取主任务下的图文任务
            $task_shop_images = $this->RTaskShopImageAccess->getTaskShop($task_commod['id']);
            if(count($task_shop_images) == 0)
            {
                return Tool::returnJson([],419,"图文任务已经接完");
            }
            $task_shop_rand = $task_shop_images[rand(0,count($task_shop_images)-1)];
            $data['task_shop_image_id'] = $task_shop_rand['id'];
        }
        //生成子任务单号
        $task_order_num = $data['task_id']."-".rand(100000,999999);
        $data['task_order_num'] = $task_order_num;
        $data['praise_keywords_id'] = $praise_keywords_id;
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $result = $this->WTaskOrderAccess->addTaskOrder($data);
            if($result)
            {
                $task_order_id = Yii::$app->db->getLastInsertID();
                //修改可接任务数量
                $re_commod = $this->WTaskCommodAccess->modifyTaskCommod(['id' => $task_commod['id'],"task_answer" => $task_commod['task_answer'] +1,"surplus_task_num" => $task_commod['surplus_task_num'] -1]);
                if(!$re_commod)
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],423,"修改可接任务数量失败");
                }
                if(($task_commod['plat_type'] == 1 || $task_commod['plat_type'] == 2) && $task_commod['task_type'] != 4)
                {
                    //修改搜索关键字数量
                    $task_commod_keyword = $this->WTaskCommodKeywordAccess->modifyTaskCommodKeyword(['use_num'=> $use_num+1,"task_commod_keyword_id"=> $task_commod_keywords_id]);
                    if(!$task_commod_keyword)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],420,"修改搜索关键字数量失败");
                    }
                }
                $arr['task_order_num'] = $task_order_num;
                if(!empty($data['task_shop_image_id']) &&isset($data['task_shop_image_id']))
                {
                    //修改图文任务信息
                    $res_image = $this->WTaskShopImageAccess->modifyTaskShop(['id' => $data['task_shop_image_id'],'is_effect' =>1]);
                    if(!$res_image)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],421,"修改图文任务信息失败");
                    }
                }
                //判断是否是自定义评价 关键字
                if($praise_keywords_id)
                {
                    $res_parise = $this->WPraiseKeywordsAccess->modifyPraisekeywords(['id'=> $praise_keywords_id,"is_user" => 2]);
                    if(!$res_parise)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],422,"自定义评价失败");
                    }
                }
                //修改买号信息 对没有接过任务的买号
                if(empty($band['is_receive_task']))
                {
                    $taobao_res = $this->WTaoBaoAccess->modifyReceiveStatus(['tb_id' => $data['tb_id'],'is_receive_task' =>1]);
                    if(!$taobao_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],368,"修改未接单买号失败");
                    }
                }
                //添加接任务日志
                $task_order_arr = [
                    "buy_id" => $data['buy_id'],
                    "task_status" => 1,
                    "status_remark" => "已接手,待下单",
                    "remark" => '已接手',
                    "task_order_id" => $task_order_id,
                    "operator" => $buy['phone'],
                ];
                $task_order_res = $this->WBuyTaskOrderLogAccess->addTaskOrderLog($task_order_arr);
                if(!$task_order_res)
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],425,"添加买手操作日志失败");
                }
                //修改买手接任务时间
                $buy_receive = $this->WBuyUserAccess->modifySendRecieveTime(['id'=> $data['buy_id']]);
                if(!$buy_receive)
                {
                    $transaction->rollBack();
                    return Tool::returnJson([],426,"修改买手接任务时间失败");
                }

                $transaction->commit();
                return Tool::returnJson($arr,200,"成功");
            }
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"接单异常".$e->getMessage());
        }
    }


}